package com.lkx.farmershop.task;

import com.lkx.farmershop.model.entity.HotTags;
import com.lkx.farmershop.model.entity.Tag;
import com.lkx.farmershop.service.HotTagsService;
import com.lkx.farmershop.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UpdateHotTags {

    @Autowired
    private TagService tagService;
    @Autowired
    private HotTagsService hotTagsService;

    //每天0点更新热门标签
    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(cron = "0 0/3 * * * ?")
    public void handleUpdateHotTags() {
        //清除旧的热门标签
        hotTagsService.remove(null);
        // 查询usedCount最大的前xx个Tag
        List<Tag> tagList = tagService.lambdaQuery()
                .orderByDesc(Tag::getUsedCount)
                .last("limit 40")
                .list();

        List<Long> tagIds = tagList.stream().map(Tag::getId).collect(Collectors.toList());
        tagIds.forEach(tagId -> hotTagsService.save(new HotTags(tagId)));

    }

}
